layui.define(['laytpl', "laydate",'form',"element","button"], function(exports){
    const form = layui.form;
    
    class Form {
    	
        constructor(id,opt,xml){
            if( $("#"+id).length<1 ){ return $.alert(0,"容器id不存在"); }
            this.$id=id;
            this.$el=$("#"+id).addClass("xw-form");
            this.$oid= $.getRequest("oid");
            this.$mode= $.getRequest("mode");
            this.$request= $.getRequest();
            this.$grids= [];
            this.$files= [];
            this.$events = {};
            this._initOption(opt,xml);
            this._initHtml();
        }
        
        _initOption(opt,xml){
            var $th = this;
            if( $th.$el.data("data") ){
                $th.$xml = $th.$el.data("xml");
                $th.option = $th.$el.data("data");
            }else if(typeof opt == "object"){
                $th.$xml = xml;
                $th.option = opt;
            }else{
                $th.$xml = opt;
                $th.$oid = (xml && xml.oid) ||  $th.$oid;
                $th.$mode = (xml && xml.mode) ||  $th.$mode ;
                $th.$request = xml || $th.$request;
                let param={ id: $th.$id, xml: $th.$xml, mode:$th.$mode, oid:$th.$oid }
                $.ajaxs(__webConfig__.xw_form.option_url, param, function(res){
                    $th.option  = $.scriptEncode(res.data);
                },false);
            }
        }
        
        //默认配置
        get defaults (){ 
            let defaults={
                buttons:{
                    mode:1,    //是否显示  0/1/2/3/4  默认1, 0不显示, 1上左，2下右，3下中，4上右
                    button:[]
                },
                tabs:{
                    showMode:1,
                    tab:[]
                }
            }
            return $.extend(true, {}, defaults, this.option);
        }
        
        //初始化页面
        _initHtml(){
            let opt=this.defaults;
            let buttons = opt.buttons;
            let html= "";
            if(buttons.show !="false" && buttons.button[0] && (buttons.mode=="1" || buttons.mode=="4")){
                html +=this._getBtn(); 
            }
            if(opt.tabs.showMode =="1" ){
            	var _style = buttons.show =="false" || buttons.mode=="0" ? "style='height:100%;'" : '';
                html += `<div class='xw-form-formType-div'  ${_style}>${this._getFormTpl(0)}</div>`; 
            }else{
            	html += this._getTabTpl();
            }
            if(buttons.show !="false"&&buttons.button[0]&&(buttons.mode=="2"||buttons.mode=="3")){
                html +=this._getBtn(); 
            }
            this.$el.html(html);
            this._initEvent();
        }
        
        //获取按钮
        _getBtn(){
            let opt=this.defaults;
            let align="left";
            //是否显示  0/1/2/3/4  默认1, 0不显示, 1上左，2下右，3下中，4上右
            if(opt.buttons.mode==2 || opt.buttons.mode==4){
                align = "right";
            }else if(opt.buttons.mode==3){
                align = "center";
            }
            return $.trim(`<div class="xw-btnRow" style="text-align: ${align};">
            ${layui.button.getBtn(opt.buttons.button,false)}</div>`);
        }
        
        //获取选项卡
        _getTabTpl(){
            let $th=this;
            let opt=this.defaults;
            let type="", 
            	h = opt.buttons.show !="false" && opt.buttons.button[0] ? "calc(100% - 42px)" : '100%',
            	tabs='',
            	tabItem='',
            	isActive=false;
            if(opt.tabs.showMode=="2"){  type="nav"}
            if(opt.buttons.mode=="0"){  h="100%"}
            opt.tabs.tab.map(function(h,index){
            	let showMode = h.showMode || 'all';
            	let active= (h.active == 'true' && !isActive) ? 'layui-this' : '';
            	let isShow = 'display: inline-block;';
            	if(showMode != 'all' && String(h.showMode).split(',').indexOf( $th.$mode) == -1 ){
            		isShow = 'display:none;';
            	}
                tabs +=` <li class="${active}" style="${isShow}" type="${h.type}">${h.title|| "标题"}</li>`;
                tabItem+=`
                    <div class="layui-tab-item ${(h.active == 'true' && !isActive) ? 'layui-show' : '' }"
                    	style="${h.style};"
                        id="${ h.type=="form" ? (h.id || '') : '' }">
                        ${ $th._getFormTpl(index) }
                    </div>
                `;
                if(h.active=="true" || h.active==true){ isActive=true;}
            });
            var html=`
            <div class="layui-tab layui-tab-brief" lay-filter="xw-form-tab" style="height: ${h};" type="${type}">
                <ul class="layui-tab-title">${tabs}</ul>
                <div class="layui-tab-content" >${tabItem}</div>
            </div>`;
            return $.trim(html);
        }
        
        //获取form模板
        _getFormTpl(index){
            let $th=this;
            let opt=this.defaults, formData = opt.tabs.tab[index], html="",hidden="";
            //html
            if(formData && formData.type =="html" ){
                html +=`<div id="${formData.id}"></div>`;
            }
            //grid
            if(formData && formData.type =="grid" ){
                html +=`<div form-dataType="grid"
            		style="padding:0;height:100%;${formData.style}"
            		query-field="${formData.queryField}"
            		${formData.height ? "vHeight="+formData.height  : '' }
            		id="${formData.id}" 
            	>${formData.value}</div>`;
            }
            //iframe
            if(formData && formData.type =="iframe" ){
                html +=`<iframe src="" id="${formData.id}" url="${formData.url}"></iframe>`;
            }
            //form
            if(formData && formData.type=="form"){
                formData.section.map(h=>{
                    h.row.forEach(v=>{
                        if(v.type=="hidden"){
                            hidden+=`<input  type="hidden" value="${v.value}" name="${v.field}" />`;
                        }
                    });
                });
                html += `
                    <form class="layui-form" onsubmit="return false;">
                        ${hidden} ${$th._getTable(formData) }
                    </form>
                `;
            }
            return $.trim(html);
        }
        
        //获取表格数据
        _getTable(formData){
            let $th=this;
            let str = '<div class="xw-form-table">';
            formData.section.map(h=>{
                str+=`<div class="sections" style="padding:${h.padding || '10px'};" id="${h.id || ''}">`;
                
                //横线标题
                if(h.title || h.button && h.button[0]){ 
                    str+=`
                        <div class="line" style="width:100%;">
                            <h3>${h.title || "分割线"}
                                <div class="line-btn">${layui.button.getBtn(h.button || [],true)}</div>
                            </h3>
                        </div>
                    `;
                }
                
            	//单元格
                if(h.row && h.row[0]){
                    h.row.forEach(v=>{  
                    	let isReq= v.vType &&  String(v.edit) !='false' && v.type !="blank" && v.ignore !="true";
		                let title = (v.type =="blank" ? "" :  v.title) || "";
		                let cols =Number(h.cols) || Number(formData.cols) || 2;
		                let titleWidth = h.titleWidth || formData.titleWidth || 70;
		                let width =  ((100 / cols) * (v.colspan || 1)).toFixed(3);
		                width = width > 100 ? 100 : width;
		                if(["html","richtext","grid"].indexOf(v.type) != -1){ width = 100;  }
                    	if(["hidden"].indexOf(v.type) ==-1 ){ 
	                    	str+=`<div class="table-cell" 
	                    		style="width:${width}%;padding:${parseInt(v.padding) || 0}px"
	                    	>`;
		                    	//标题
		                    	if(["html","richtext","grid"].indexOf(v.type) == -1  || v.showTitle=="true"){
		                    		str += `
			                    		<div class="table-title ${isReq ? 'f-orage' : '' }"
			                    			style="width:${titleWidth}px;"
			                    		>${title}</div>
			                    	`;
			                    	titleWidth = Number(titleWidth) + 20;
		                    	}else{
		                    		titleWidth = 20;
		                    	}
		                    	//录入区
		                    	let classs = (v.remark || v.type == "percent") ? 'remark' : '';
		                   		str+=`
			                        <div class='table-input ${classs}' style='width:calc(100% - ${titleWidth}px);'>
			                        	${$th._getInputType(v,formData)}
			                        </div>
			                    `;
	                        str+=`</div>`;
                       	}
                    });
                }
                
	            str+="</div>";    
            });
            
            str+="</div>";
            return str;   
        }
        
        //获取输入类型
        _getInputType(v,formData){
            let  str="";
            let  formConfig = (window.__webConfig__ && __webConfig__.xw_form) || {};
            let  defaultAcc = v.acc || formConfig.numberAcc  || 2;
            let  enabledPermil = formConfig.enabledPermil === false ? false : true;
            let  autocomplete = formConfig.autocomplete === true ? "on" : "off";
            if( v.type=='number' || v.type=='money'){
            	v.value = Number( (v.value || 0) ).toFixed( defaultAcc );
            	v.type = 'number';
            }
            if(enabledPermil && v.enabledPermil !== 'false' && (v.type=='number' || v.type=='money')){
            	v.value = $.commafy(v.value);
            }
            switch(v.type){
                case "text":
                case "password":
                case "number":
                case "money":
                case "percent":
                  	if(v.type == "percent"){ v.max = 100; v.min = 0; v.remark= v.remark || '%'; 	}
                    str+=`
                        <input type="text" 
                        	class="layui-input ${v.type=='number' || v.type=='money' ? 'align-right' : ''}"
                        	form-dataType="${v.type || 'text'}"
                        	autocomplete="${ v.autocomplete || autocomplete}"
                            style="${ (v.remark && !v.style) ? 'padding-right: 0px;' : v.style }"
                            ${v.id? "id="+v.id  : '' }
                            acc = "${defaultAcc}"
                            value="${v.value}" 
                            name="${v.field}"
                            max-length="${v.maxLength || ''}"
                            max="${v.max || ''}"
                            min="${v.min || ''}"
                            title="${v.tips || ''}"
                            enabledPermil="${v.enabledPermil || ''}"
                            placeholder="${v.placeholder || v.desc  || formConfig.descEqTitle && v.title || ''}" 
                           ${v.vType ? "dataType="+v.vType  : '' }
                           	ignore = "${v.ignore && v.ignore == "true" ? 'ignore' : '' }"
                           	errormsg = "${v.errormsg || '格式不正确'}"
                            edit="${v.edit}"
                            chkpwdField="${v.chkpwdField}"
                            ${v.edit == "false" ?  "disabled" : ""}
                        />
                    `;
                    if(v.remark) str+=`<span class='xw-percents'>${v.remark}</span>`;
                    break;
                case "textarea":
                    str+=`
                        <textarea  class="layui-textarea" form-dataType="textarea"
                            onclick="if($(this).attr('edit')!='false'){${v.onClick}}"
                            style="${v.style}"
                            ${v.id? "id="+v.id  : '' }
                            max-length="${v.maxLength}"
                            name="${v.field}"
                            title="${v.tips || ''}"
                            placeholder="${v.placeholder || ''}" 
                            ${v.vType ? "dataType="+v.vType  : '' }
                            ignore = "${v.ignore && v.ignore == "true" ? 'ignore' : '' }"
                            errormsg = "${v.errormsg || '格式不正确'}"
                            edit="${v.edit}"
                            ${v.edit == "false" ?  "disabled" : ""}
                        >${ (v.value).replace(/n/g,"&#10;") }</textarea>
                    `;
                    break;
                case "checkbox":
                    let checkboxs = v.option ? v.option.map(h=>{
                        return `
                            <input title="${h.label}"  type="checkbox" lay-skin="primary"
                            	form-dataType="checkbox"
                                lay-filter="${$.createGuid()}"
                                onClick='${v.onClick}'
                                ${v.id? "id="+v.id  : '' }
                                value="${h.value}" 
                                name="${v.field}" 
                               ${v.vType ? "dataType="+v.vType  : '' }
                                ignore = "${v.ignore && v.ignore == "true" ? 'ignore' : '' }"
                                errormsg = "${v.errormsg || '格式不正确'}"
                                edit="${v.edit}"
                                ${v.edit == "false" ?  "disabled" : ""}
                                ${ String(v.value).split(',').indexOf(h.value) != -1 ?  'checked' : ''}
                            />
                        `;
                    }).join("") : '';
                    str +=`<div class="xw-input">${checkboxs}</div>`;
                    break;
                case "radio":
                    let radios = v.option ? v.option.map(h=>{
                        return `
                            <input title="${h.label}"  type="radio"
                            	form-dataType="radio"
                                lay-filter="${$.createGuid()}"
                                onClick='${v.onClick}'
                                ${v.id? "id="+v.id  : '' }
                                value="${h.value}" 
                                name="${v.field}" 
                                ${v.vType ? "dataType="+v.vType  : '' }
                                ignore = "${v.ignore && v.ignore == "true" ? 'ignore' : '' }"
                                errormsg = "${v.errormsg || '格式不正确'}"
                                edit="${v.edit}"
                                ${v.edit == "false" ?  "disabled" : ""}
                                ${ String(v.value).split(',').indexOf(h.value) != -1 ?  'checked' : ''}
                            />
                        `;
                    }).join("") : '';
                    str +=` <div class="xw-input">${radios}</div>`;
                    break;
                case "select":
                    let options = v.option ? $.trim(v.option.map(h=>{
                        let selected = (v.value || '').indexOf(h.value) != -1 ?  'selected' : '';
                        return `<option value="${$.trim(h.value)}"  ${selected}>${h.label}</option>`;
                    }).join("")) : '';
                    str +=` <select form-dataType="select"
                            lay-filter="${$.createGuid()}"
                            onClick='${v.onClick}'
                            ${v.id? "id="+v.id  : '' }
                            name="${v.field}"
                            type="${v.type}" 
                            value="${v.value}" 
                            ${v.vType ? "dataType="+v.vType  : '' }
                           	ignore = "${v.ignore && v.ignore == "true" ? 'ignore' : '' }"
                           	errormsg = "${v.errormsg || '格式不正确'}"
                            edit="${v.edit}"
                            title="${v.tips || ''}"
                            ${v.edit == "false" ?  "disabled" : ""}
                        >${ options}</select>`;
                    break;
                case "datetime":
                    str +=` 
                    	<input class="layui-input" datetime="datetime" readonly
                    		form-dataType="datetime"
                            style="${v.style}"
                            ${v.id? "id="+v.id  : '' }
                            type="text"
                            format="${v.format || 'yyyy-MM-dd'}"
                            value="${v.value}" 
                            name="${v.field}" 
                            placeholder="${v.placeholder || '请选择时间'}" 
                            ${v.vType ? "dataType="+v.vType  : '' } 
                           	ignore = "${v.ignore && v.ignore == "true" ? 'ignore' : '' }"
                           	errormsg = "${v.errormsg || '格式不正确'}"
                            on-click="${v.onClick}"
                            min="${v.min}"
                            max="${v.max}"
                            edit="${v.edit}"
                            range="${v.range}"
                            title="${v.tips || ''}"
                            ${v.edit == "false" ?  "disabled" : ""}
                    	/>
                    `;
                    break;
                case "link"://完善
                    let onClick = `$.openWin("${v.url}", "sName",${ JSON.stringify((v.openArea || '').split(',')) } )`;
                    if( v.onClick ){
                        onClick = v.onClick;
                    }else if(v.openArea == "full" ){
                        onClick = `$.openFullWin("${v.url}", "sName")`;
                    }
                    str +=` <a class="xw-input ${v.mode ==2 ? '' : 'link'}" href="javascript:void(0);"
                            onclick='${onClick}'
                            style="${v.style}"
                            ${v.id? "id="+v.id  : '' }
                            value="${v.value}" 
                            name="${v.field}" 
                            >${v.value}</a>`;
                    break;
                case "search":
                    let val=String(v.value).split(',').map(h=>{
                    	let html= `<span><u onclick="${v.onValClick || v.onClick}" >${h}</u></span>`;
                    	if(String(v.showCloseBtn)!="false" && v.edit !="false" && h){
                    		html =  `
	                        	<span>
		                        	<u onclick="${v.onValClick || v.onClick}" >${h}</u>
		                        	<sup class="span-close">x</sup>
	                        	</span>	
	                        `;
                    	}
                    	return html;
                    }).join('');
                    str +=`
                        <div class="select-search-body">
                            <div class="select-search-input" type="search"
                            	form-dataType="search"
                            	onValClick="${v.onValClick || v.onClick}"
                            	showCloseBtn="${v.showCloseBtn}"
                                name="${v.field}" 
                                edit="${v.edit}" 
                                data-value="${v.value}"
                                ${v.vType ? 'dataType=chooseBox'  : '' }
                                ignore = "${v.ignore && v.ignore == "true" ? 'ignore' : '' }"
                                errormsg = "${v.errormsg || '格式不正确'}"
                            >${val}</div>
                            <button type="button" class="select-search-icon" 
                            	onclick="if($(this).prev().attr('edit')!='false'){${v.onClick}}"
                            ><i class="iconfont">&#xe651;</i></button>
                        </div>
                    `;
                    break;
                case "file":
                	let fileId = $.createGuid();
                    str +=` 
                    	<div class='fileUploadContainer'
                    		form-dataType="file"
                    		id="${v.id || fileId}" 
                    		name="${v.field}" 
                    		edit="${v.edit || ''}"
                    		fkGuid="${v.fkGuid}"
                    		fkGuidField="${v.fkGuidField}"
                    		ywName="${v.ywName || 'file'}"
                    		fkType="${v.fkType || '文件'}"
                    		showSwiper="${v.showSwiper || ''}"
                    		accept="${v.accept || ''}"
                    		max="${v.max || 0}"
                    		min="${v.min || 0}"
                    		${v.vType ? 'dataType=file'  : '' }
                    	>
                    		<a href="javascript:;" class="fileUpload-link" >相关附件(0)</a>
                    	</div>
                    `;
                    break;
                case "multiSelect":
                case "linkage":
                    let multiData = v.option ? $.trim(v.option.map(h=>{
                        let selected = v.value.indexOf(h.value) != -1 && h.value ?  'selected' : '';
                        return `<option value="${$.trim(h.value)}" ${selected}>${h.label}</option>`;
                    }).join("")) : '';
                    str +=` 
                        <select xm-select="${$.createGuid()}"
                        	form-dataType="${v.type}"
                            xm-select-height="30px" 
                            xm-select-show-count="${v.showCount || 2}"
                            name="${v.field}" 
                            data-value="${v.value}"
                            edit="${v.edit}"
                            onClick="${v.onClick}"
                            ${v.vType ? "dataType="+v.vType  : '' }
                            ignore = "${v.ignore && v.ignore == "true" ? 'ignore' : '' }"
                            errormsg = "${v.errormsg || '格式不正确'}"
                            >${multiData}</select>`;
                    break;
                case "richtext":
                    let guid=$.createGuid();
                    let richtextValue = $.htmlDecode(v.value);
                    str +=` 
                        <script type="text/plain" id="${v.id || guid}" name="${v.field}"> 
                            ${richtextValue} 
                        </script>
                        <input type="hidden"  xw-richtext
                        	form-dataType="richtext"
                            name="${v.field}" 
                            ue-id="${v.id ||  guid}" 
                            value="${v.value}" 
                            edit="${v.edit}"
                        />
                    `;
                    break;
                case "selectTree":
	                str += `
	                	<input form-dataType="selectTree" type="text" class="layui-input" readonly
	                		id="${$.createGuid()}"
	                        name="${v.field}"
	                        data-url="${v.dataUrl || ''}"
	                        text-field="${v.textField || ''}"
	                        id-field="${v.idField || ''}"
	                        parent-field="${v.parentField || ''}"
	                        show-checkbox= "${v.showCheckbox || ''}"
	                        disableParentNode = "${v.disableParentNode || ''}"
	                        expandNode = "${v.expandNode || 1}"
	                        edit="${v.edit}"
	                        value="${v.value}" 
	                        ${v.edit == "false" ?  "disabled" : ""}
	                       ${v.vType ? "dataType="+v.vType  : '' }
	                    />
	            	`;
                    break;
                case "grid":
                    str += ` 
                   		<div style="display:flex;width: 100%;height: 100%;">	
	                    	<div form-dataType="grid"
	                    		style="padding:0;width: 100%;${v.style}"
	                    		${v.height ? "vHeight="+v.height  : '' }
	                    		query-field="${v.queryField}"
	                    		id="${v.id}" 
	                    	>${v.value}</div>
                    	</div>
                    `;
                    break;   
                case "region":
                	let regionGuid= $.createGuid();
                	let regionFormat = (v.format || '省,市,区').split(',');
                	let province = !v.edit ? String(v.value || '').split(',')[0] : '';
                	let city =  !v.edit ?  String(v.value || '').split(',')[1] : '';
                	let county =  !v.edit ? String(v.value || '').split(',')[2] : '';
                    str += ` 
                    	<div class="layui-form-item" form-dataType="region" 
                    		id="${regionGuid}"
                    		edit="${v.edit}"
                    		region-name = "${v.field}"
                    		format="${v.format}"
                    	><input type="hidden" name="${v.field}" class="collect" value="${v.value}" />
                    		${(function(){
                			  	if(regionFormat.indexOf('省') != -1) return `
                				<div class="layui-input-inline" style="margin-right: 10px;">
					                <select name="province" class="province-selector" data-value="${province}" 
					                	${v.edit == "false" ?  "disabled" : ""}
					                >
					                    <option value="${province}" selected>${province}</option>
					                </select>
					            </div>`;
                    		}())}
				            ${(function(){
                			  	if(regionFormat.indexOf('市') != -1) return `
				            	<div class="layui-input-inline" >
					                <select name="city" class="city-selector" data-value="${city}" 
					                	${v.edit == "false" ?  "disabled" : ""}
					                >
					                    <option value="${city}" selected>${city}</option>
					                </select>
					            </div> `;
                    		}())}
				            ${(function(){
                			  	if(regionFormat.indexOf('区') != -1) return `
				            	 <div  style="margin-left: 10px;">
					                <select name="county" class="county-selector" data-value="${county}" 
					                	${v.edit == "false" ?  "disabled" : ""}
					                >
					                    <option value="${county}" selected>${county}</option>
					                </select>
					            </div>`;
                    		}())}
				        </div>
                    `;
                    break;
                case "img":
                	let imgId = $.createGuid();
                	let descriptions = (formData.section[0].row[0].value || '').split('|');
                 	let imgVal = v.value ? String(v.value).split(',').map((h,index)=>{
                 		//let description = descriptions[index] || '';
                 		let description =  '';
                 		let r =`${__root__}/public/images/loading-1.gif`;
                    	return  `
                    		<div class="layui-form-item-body" style="background: url(${r}) no-repeat center;">
                        		<div  class="layui-form-item-img">
                        			<div class="layui-form-item-img-mask">
                        				<i class="iconfont yan">&#xe663;</i>
                        				${v.edit == 'false' ? '' : '<i class="iconfont del">&#xe628;</i>' }
                        				<i class="iconfont edit">&#xe621;</i>
                        			</div> 
                        			<div class="layui-form-item-img-desc">${description}</div> 
                        			<img src='${h}'/>
                        		</div>
                        	</div>
                        `;
                   	}) : [];
                   	let is_upload_hide = 'hide';
                   	if(!v.value || imgVal.length < v.max || !v.max || v.max == '0'){
                   		is_upload_hide = '';
                   	}
                   	if(v.edit != "false"){
                   		imgVal.push(`
	               			<div class="layui-form-item-img-upload ${is_upload_hide}" 
	               			id="${v.id || imgId}">上传</div>
	               		`);
                   	}
                   	imgVal = imgVal.join('');
                    str +=` 
                    	<div form-dataType="img" style="display: flex;"
                    		name="${v.field}" 
                    		edit="${v.edit || ''}"
                    		fkGuid="${v.fkGuid}"
                    		fkGuidField="${v.fkGuidField}"
                    		ywName="${v.ywName || 'file'}"
                    		fkType="${v.fkType || '图片'}"
                    		showDesc="${v.showDesc}"
                    		showGallery="${v.showGallery}"
                    		showSwiper="${v.showSwiper || ''}"
                    		accept="${v.accept || ''}"
                    		max="${v.max || 0}"
                    		min="${v.min || 0}"
                    		${v.vType ? 'dataType=file'  : '' }
                    	> <input type="hidden" name="${v.field}" class="collect" value="${v.value}" />
                    		${imgVal}
                    	</div>
                    `;
                    break;    
                case "html":
                    str += ` 
                    	<div id="${v.id}" style="padding:0 0 0 6px;${v.style}"
                    		${v.height ? "vHeight="+v.height  : '' }
                    	>${v.value}</div>
                    `;
                    break;
                default:
            }
            return $.trim(str).replace(/undefined/g,"").replace(/\ +/g, " "); 
        }
        
        //初始化事件
        _initEvent(type){
            var $th = this;
            var $el = $th.$el;
            
            //初始化layui.from事件
            form.render(null,null,'.xw-form');
            
            //省市级控件
            if($el.find("[form-dataType='region']").length!=0){
            	$.each( $el.find("[form-dataType='region']") , function(index,o) {
            		let id = $(o).attr('id');
            		let regionFormat = ( $(o).attr('format') || '省,市,区' ).split(',');
            		let vals = $("#"+id).find('.collect').val().split(',');
            		layui.layarea.render({
			            elem:"#"+id,
			            disabled: $(o).attr('edit') =='false' ? true : false,
			            data: {
					        province: vals[0] || '',
					        city: vals[1] || '',
					        county: vals[2] || '',
					    },
			            change: function (res) {
			            	let val = [];
			            	if(regionFormat.indexOf('省') != -1 ) val.push(res.province);
			            	if(regionFormat.indexOf('市') != -1 ) val.push(res.city);
			            	if(regionFormat.indexOf('区') != -1 ) val.push(res.county); val = val.join(",");
			            	$("#"+id).find('.collect').val( val );
			            	$th.callEvent("input", $("#"+id).find('.collect').attr("name"), $("#"+id).find('.collect'), val);
			            }
			        });
            	});
            	if(type=="region") return false;
            }
            
            //上传附件
            if($el.find(".fileUploadContainer").length!=0){
            	$.each($el.find(".fileUploadContainer"), function(index,o) {
            		let fileId = $(this).attr("id") || $.createGuid();  $(this).attr("id",fileId);
            		let fkGuidField = $(this).attr("fkGuidField");
            		let fkGuid = fkGuidField ? $th.getValue(fkGuidField) : $(this).attr("fkGuid");
            		let upload = layui.uploads.init({
            			id:fileId,					//必填，附件主键
            			fkGuid: fkGuid || '000-000',	//必填，附件主键
            			ywName: $(this).attr("ywName"),         	//必填，业务过程名称    
            			fkType:$(this).attr("fkType"),			    	//必填，附件类型
            			multiple:$(this).attr("multiple") ||  true,
            			maxCount:0,
            			mode:$(this).attr("mode") || 1,
            			actionCode:window.__mode || 0, //按钮权限 0/1/2/3
            			errorInfo: '请先选择',        //fkGuid不存在时的报错信息,非必填
            			showType:"grid",            //列表展示方式: grid,paved
            			max: $(this).attr("max") || 0,
            			min: $(this).attr("min") || 0,
            			accept:$(this).attr("accept") || 'file',
            			showSwiper: Boolean($(this).attr("showSwiper")) || false,
            		});
            		if($(o).attr('edit')=="false" && upload){ upload.setActionCode('3'); }
            		$(this).data("object",upload);
            		$th.$files[fileId] = upload;
            	});
            }
            
            //下拉多选框初始化
            if($el.find("select[xm-select]").length!=0){
                //https://hnzzmsf.github.io/example/example_v4.html#select_on
                layui.formSelects.render();
                $.each($el.find("select[xm-select]"), function(index,o) {
                    let id=$(o).attr("xm-select");
                    let click=$(o).attr("onClick");
                    let edit=$(o).attr("edit");
                    let datatype=$(o).attr("datatype");
                    $(o).removeAttr("datatype");
                    $el.find("[fs_id="+id+"]").attr("data-value",$(o).attr("data-value"));
                    if(datatype){ $el.find("[fs_id="+id+"]").attr("datatype","chooseBox");  }
                    if(edit=="false"){
                        layui.formSelects.disabled(id);
                    }else{
                        layui.formSelects.undisabled(id);
                    }
                    //['select', 'remove', 'reverse']
                    layui.formSelects.btns(id,['select','remove'],{show: '', space: '10px'});
                    layui.formSelects.on(id, function(e,data){
                        let vals = $.map(data,function(h){ return h.value; });
                        $el.find("[fs_id="+id+"]").attr("data-value",vals);
                        if(click){ eval(click) }
                        $th.callEvent("input",$(o).attr("name"),$(o), $(o).val() );
                    },true);
                });
            }
            
            //初始化下拉树
            if($el.find("[form-dataType='selectTree'][edit='true']").length!=0){
            	$.each($el.find("[form-dataType='selectTree']"), function() {
            		var othis = $(this);
            		var tree =  layui.selectTree.render({
		                elem: othis,
		                textField: othis.attr('text-field'),
		                idField: othis.attr('id-field'),
		                parentField: othis.attr('parent-field'),
		                data: othis.attr('data-url') ,
		                isList:true,                                               
		                expandNode: othis.attr('expandNode') || 1,                                 
		                showCheckbox: $(this).attr('show-checkbox') || false,  
		                accordion: $(this).attr('accordion') || false, 		                          
		                showIcon: false,
		                disableParentNode: $(this).attr('disableParentNode') == 'false' ? false : true,
		                loadSuccess:function(data){                 
							tree.tree.selectNode(othis.attr('id-field'), othis.val() );
			            }
		            });
            	});
            };
            
            //初始化grid
            if($el.find("[form-dataType='grid']").length!=0){
            	$.each($el.find("[form-dataType='grid']"), function(index,o) {
            		let id = $(this).attr("id");
	            	let queryField = $(this).attr("query-field");
	            	let value = $th.getValue(queryField);
	            	if(!$th.$grids[id]){
	            		$th.$grids[id] = layui.grid.render(id);  //参2非必填，默认当前config.xml
			            if($th.$grids[id].$search){
			            	$th.$grids[id].$search.$el.find('.xw-search').prepend(`
			            		<div class='layui-input-inline' style='display: none;'>
			            			<input type="hidden" data-opera="=" value="${value}" name="${queryField}"/>
			            		</div>
			            	`);
			            }else{
			            	$th.$grids[id].load( queryField ? [{"field": queryField ,"opera":"=","value":value }] : []);
			            }
	            	}
            	});
            }
            
            //绑定时间事件
            if($el.find("input[datetime]").length!=0){
                $.each($el.find("input[datetime]"), function(index,o) {
                    let click=$(o).attr("on-click");
                    let edit=$(o).attr("edit");
                    let min=$(o).attr("min");
                    let max=$(o).attr("max");
                    let format=$(o).attr("format");
                    layui.laydate.render({
                        elem: o,
                        format: format || 'yyyy-MM-dd', //可任意组合 yyyy-MM-dd HH:mm:ss
                        range:$(this).attr("range") == "true" ? true : false,
                        position: 'abolute',
                        min: !min  || min == "undefined"?  "1900-1-1" : min,
                        max: !max || max == "undefined" ?  "2199-12-31" : max,
                        showBottom:true,
                        trigger: 'click', //呼出控件的事件
                        type: $th._getFormat(format),
                        done: function(value, date, endDate){
                            setTimeout(function(){ 
                                if(click && edit!="false"){ eval(click) }
                                $th.callEvent("input",$(o).attr("name"),$(o), $(o).val() );
                            },5)
                        }
                    });
                });
            }
            
            //监听复选框事件
            if($el.find("input[type='checkbox']").length!=0){
                $.each($el.find("input[type='checkbox']"), function(index,o) {
                    let click=$(o).attr("onClick");
                    let filter=$(o).attr("lay-filter");
                    let edit=$(o).attr("edit");
                    form.on('checkbox('+filter+')', function(data){
                        setTimeout(function(){
                            if(click && edit!="false"){ eval(click) }
                            $th.callEvent("input",$(o).attr("name"),$(o), $(o).val() );
                        },5);
                    });  
                });
            }
            
            //监听单选框事件
            if($el.find("input[type='radio']").length!=0){
                $.each($el.find("input[type='radio']"), function(index,o) {
                    let click=$(o).attr("onClick");
                    let filter=$(o).attr("lay-filter");
                    let edit=$(o).attr("edit");
                    form.on('radio('+filter+')', function(data){
                        setTimeout(function(){
                            if(click && edit!="false"){ eval(click) }
                            $th.callEvent("input",$(o).attr("name"),$(o), $(o).val() );
                        },5);
                    });  
                });
            }
            
            //监听下拉框事件
            if($el.find("select[onClick]").length!=0){
                $.each($el.find("select[onClick]"), function(index,o) {
                    let click=$(o).attr("onClick");
                    let filter=$(o).attr("lay-filter");
                    let edit=$(o).attr("edit");
                    form.on('select('+filter+')', function(data){
                        setTimeout(function(){
                            if(click && edit!="false"){ eval(click) }
                            $th.callEvent("input",$(o).attr("name"),$(o), $(o).val() );
                        },5);
                    });  
                });
            }
           
            //搜索框事件
            if($el.find(".select-search-input").length!=0){
            	$(document).on("click",".select-search-input sup",function(){
            		var parents =  $(this).parents(".select-search-input");
            		$(this).parents("span").remove();
            		parents.attr("data-value",
            			$.map(parents.find("u"), function(h) {
            				return $.trim( $(h).text() );
            			}).join(',')
            		);
            	});
            }
            
            //限制输入最大根数
            if($th.$el.find("[max-length]").length!=0){
            	$th.$el.find("input[type='text'],textarea").bind("input propertychange", function () {
	                let maxlength = $(this).attr("max-length");
	                if(maxlength && String(maxlength) != "-1" && $(this).val().length > maxlength){
	                    $(this).val( $(this).val().substring(0,maxlength))
	                    $th._tips($(this),'最多只能输入'+maxlength+'个字体！');
	                }
	            });
            }
            
            //设置number类型最大值和只能输入数字
            $th.$el.find(".layui-form input[form-datatype='number']").bind("input propertychange",function () {
            	var max = $(this).attr("max"), min = $(this).attr("min"),acc = $(this).attr("acc") || 2;
            	var value = $(this).val();
            	if(! /^(\-|\+)?\d+(\.\d+)?$/.test( value ) ){  //限制必须录入数字
            		value = $th.clearNoNum(value);
            		$(this).val( value );
            	}
            	if(max && value > Number(max)){
            		$(this).val( Number(max) );
            		$th._tips($(this),"不能大于"+Number(max)+"！");
            	}
            	if(min && Number(min) > value){
            		$(this).val( Number(min) );
            		$th._tips($(this),"不能小于"+Number(min)+"！");
                }
            });
            //输入的时候转为number类型
            $th.$el.find(".layui-form input[form-datatype='number']").unbind('focus').focus(function(e){
        		$(this).val( $.delcommafy( $(this).val() ) );
            });
            //鼠标离开输入框的时候，转换类型为text与转换数据为千分号格式
            $th.$el.find(".layui-form input[form-datatype='number']").unbind('blur').blur(function(){
            	var acc = $(this).attr("acc") || 2;
            	var enabledpermil = $(this).attr("enabledpermil");
            	var val = Number( $(this).val() ).toFixed( acc );
            	$(this).attr('type','text');
            	if(enabledpermil != "false"){
            		$(this).val( $.commafy( val ) );
            	}else{
            		$(this).val(val);
            	}
            });
            
            //html类型自动高度
            if($th.$el.find("div[vheight]").length!=0){
                $th._divAutoHeight();
            }
            
            //初始化富文本
            if($th.$el.find("[xw-richtext][ue-id]").length!=0){
                $th._initRichtext();
            }
            
            //tab点击事件
           	layui.element.on('tab(xw-form-tab)', function(e){
           		let $that = $(e.elem.context);
           		let index = $that.index();
           		let $container = $that.parents('ul').siblings('.layui-tab-content')
           									.find('.layui-tab-item').eq(index);
           		if($that.attr("type") == 'iframe'){
           			$container.find('iframe').attr("src",$container.find('iframe').attr("url"))
           		}
           		if($th._tabClickCallbackFn){ $th._tabClickCallbackFn($that); }
            	layer.closeAll('tips');
            });
            
            //监听输入事件
            $th.$el.find("input,textarea").bind("input propertychange", function () {
        		$th.callEvent("input",$(this).attr("name"),$(this), $(this).val() );
        	});
        	
        	//imgType
            if($el.find("[form-dataType='img']").length!=0){
            	$th._initImgs($el);
            }
        }
        
        //初始化图片上传控件
        _initImgs($el){
        	//查看
        	$el.find("[form-dataType='img']").on('click','.yan',function(){
        		$.photoImg( 
        			$.map($(this).parents("[form-datatype='img']").find('img'),function(h){
            			if($(h).attr('src')) return $(h).attr('src');
            		}).join(','),
            		$(this).parents('.layui-form-item-body').index() - 1
            	);
        	});
        	//编辑
        	$el.find("[form-dataType='img']").on('click','.edit',function(){
        		var parent = $(this).parents(".layui-form-item-img");
        		let src = $(this).parents('.layui-form-item-img').find('img').attr('src');
        		$.ajaxs('/admin/soft/upload/getDesc',{file_path:src}).then(function(res){
            		function yesFn(index,oLayer){
            			let desc = $(oLayer).find('#upload_textarea_info1').val() || '';
            			$.ajaxs('/admin/soft/upload/updateDesc',{file_path:src,desc:desc}).then(function(res){
            				$(parent).find('.layui-form-item-img-desc').text(desc);
            				layer.close(index);
            			});
            		}
            		var html = `
	            		<div class="table-cell" style="width:100.0%;padding:10px">
	                    	<div class="table-title " style="width:120px;">图片指向地址</div>
	                  		<div class="table-input" style="width:100%">
	                        	<textarea class="layui-textarea"  id="upload_textarea_info1" >
	                        		${res.data}
	                        	</textarea>
	                        </div>
	                    </div>
                    `;
            		$.openModalDialog(html,"编辑指向地址",null,yesFn,['450px', '250px']);
        		});
        	});
        	//删除
        	$el.find("[form-dataType='img']").on('click','.del',function(){
        		var that = $(this);
        		var src = $(this).parents(".layui-form-item-img").find('img').attr('src');
        		var parent = $(this).parents("[form-dataType]");
        		$.confirm("删除图片", function(index){
        			that.parents(".layui-form-item-body").remove();
        			parent.find('.hide').removeClass("hide");
        		    var newVal = $.map(parent.find('input.collect').val().split(','),function(h){
        		    	if(h!=src) return h;
        		    });
        			parent.find('input.collect').val(newVal)
        			layer.close(index);
        		});
        	});
        	//初始化上传
        	$.each($el.find(".layui-form-item-img-upload"),function(){
        		let parent = $(this).parents('[form-dataType]');
        		if(parent.attr("edit") == 'false' || $(this).attr('uploads-index') > 0){
        			return false;
        		}
        		let that = $(this); $(this).attr('uploads-index',1);
    			let loadImg = function(parent,src){
    				if(that.is(".hide")) return false;
        			let desc = $('#upload_textarea_info').val();
        			let newVal = parent.find('input.collect').val().split(','); 
        			newVal = $.map(newVal,function(h){ if(h) return h }); 
        			newVal.push(src);
        			parent.find('input.collect').val( newVal.join(',') );
             		let r =`${__root__}/public/images/loading-1.gif`;
                	let imgVal  = `
                		<div class="layui-form-item-body" style="background: url(${r}) no-repeat center;">
                    		<div  class="layui-form-item-img">
                    			<div class="layui-form-item-img-mask">
                    				<i class="iconfont yan">&#xe663;</i>
                    				<i class="iconfont del">&#xe628;</i>
                    				<i class="iconfont edit">&#xe621;</i>
                    			</div> 
                    			<div class="layui-form-item-img-desc">${desc || ''}</div> 
                    			<img src='${src}'/>
                    		</div>
                    	</div>
                    `;
                    that.before(imgVal);
                    let length = parent.find(".layui-form-item-body").length;
                    if(length >= parent.attr("max") && parent.attr("max") > 0){
                    	that.addClass("hide");
                    }
        		}
        		let uploadSuccess = function (parent,uploadObj,that,index){
            		uploadObj.uploadSuccess(function(res){ 
            			loadImg(parent,res.data.src) 
            			if(index) layer.close(index);
            		});
            	};
            	let getUploadObj = function(id,parent,type){
            		let obj = {
	                    id:id,					        //必填，附件主键
	                    fkGuid: parent.attr("fkGuid") || 'layui-form-item-img-upload',//必填，附件主键
	                    ywName: parent.attr("ywName"),   //必填，业务过程名称    
	                    fkType: parent.attr("fkType"),	        //必填，附件类型
	                    multiple:false,                                        
	                    maxCount:1,
	                    actionCode:window.__mode || 0,         //按钮权限 0/1/2/3
	                    createBtn:false,
	                    accept:'images'              //允许上传的文件,images,file,video（视频）、audio（音频）
	            	}
            		if(type==2){ obj.auto = false; obj.bindAction = '.layui-layer-btn0';}
            		return layui.uploads.init(obj);
            	}
        		if( parent.attr('showDesc') == 'true'){
        			$(this).click(function(){
	            		let  id = $(this).attr('id') || $(this).attr('rid') ; $(this).attr('id','');$(this).attr('rid',id);
	            		function successFn(index){
			            	uploadSuccess(parent,getUploadObj(id,parent,2),that,index);
	            		}
	            		function yesFn(index,olayui){
	            			if( $(olayui).find('.layui-upload-choose').length==0 ){
	            				$.toast(0,'请先选择图片！');
	            			}
	            		}
	            		var html = `
		            		<div class="table-cell" style="width:100.0%;padding:10px">
		                    	<div class="table-title " style="width:120px;">图片指向地址</div>
		                  		<div class="table-input" style="width:100%">
		                        	<textarea class="layui-textarea"  id="upload_textarea_info" ></textarea>
		                        </div>
		                        <div class="layui-form-item-img-upload-select" id='${id}'>选择图片</div>
		                    </div>
	                    `;
	            		$.openModalDialog(html,"上传",successFn,yesFn,['450px', '300px']);
	            	});
        		}else if( parent.attr('showGallery') != 'false' ){
        			$(this).click(function(){
        				$.openWin('/system/gallery/index?', '上传', ['820px', '500px']);
        				window.galleryUploadsCallback = function(data){
        					$.map(data,function(o){ loadImg(parent,__root__+o.src); });
        				}
        			});
        		}else{
	            	uploadSuccess(parent,getUploadObj($(this).attr('id'),parent) ,that);
        		}
        	});
        }
        
        //转为number
        clearNoNum (value){
        	var t = value.charAt(0);
	    	value = value.replace(/[^\d.]/g, "").replace(/^\./g, "").replace(/\.{2,}/g, ".");
	    	value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
	    	if (t == '-')  value = '-' + value;
	    	return value;
        }
        
        //提示
        _tips(that,text){
        	layer.tips(text,$(that),{
                tips: [1, '#f1355e'],
                time: 1500,
                tipsMore: false,
            });
        }
        
        //自动高
        _divAutoHeight(is){
            var $th=this;
            $.each($th.$el.find("div[vheight]"), function(index,o) {
                let height= Number($(o).attr("vheight")) < 0 ? 
                $(o).parents('.xw-form').height() + Number($(o).attr("vheight")) : $(o).attr("vheight");
                $(o).css("height",height);
            });
            if(!is){
            	$(window).unbind("resize").on("resize",function(){
	                $th._divAutoHeight(true);
	            });
	            var $width = $th.$el[0].clientWidth;
	            var $height = $th.$el[0].clientHeight;
	            setInterval(function  () {
	                var _width = $th.$el[0].clientWidth;
	                var _height = $th.$el[0].clientHeight;
	                if( _width != $width || _height != $height){
	                    if(_width > 0 && $(":animated").length==0){
	                    	$th._divAutoHeight(true);
	                      	$width= _width;
	                        $height=_height;
	                    }
	                }
	            },20);
            }
        }
        
        //富文本
        _initRichtext(){
            var $th=this;
            $.each($th.$el.find("[xw-richtext][ue-id]"), function(index,e) {
                var  id = $(this).attr("ue-id")
                var  edit = $(this).attr("edit");
                var  ue = $(this).data("object");
                if( !ue ){
	            	ue = new layui.richtext.init(id);
	                ue.contentChange(function(editor){
	                    $(`input[ue-id='${id}']`).val(editor);
	                });
	                $(this).data("object",ue);
                }
             	ue.loadSuccess(function(){
                    function _fn(){
                        let h = 48;
                        if($th.defaults.tabs.showMode==3){  h+=40; }
                        $("#"+id).css("height",window.innerHeight - h); 
                    }; _fn();
                    $(window).unbind("resize").on("resize",function(){
                        _fn();
                    });
                    edit == "false" ? ue.setDisabled() : ue.setEnabled();
                });
            });
        }
        
        //获取时间格式
        _getFormat(format){
            let _format ='date';
            if(format.indexOf("d") == -1 && format)
                _format='month';
            if(format.indexOf("M") ==-1 && format)
                _format='year';
            if(format.indexOf("H") !=-1)
                _format='datetime';
            if(format == 'HH:mm:ss' || format == 'HH:mm' || format == 'HH:mm:ss' || format == 'HH')
                _format='time';    
            return _format;
        }
        
        /**
        *  点击选项卡的回调
        * @access public
        * @param {[function]}  
        * @return null 
        */
        tabClick(callbackFn){
        	this._tabClickCallbackFn = callbackFn;
        }
        
        /**
        *  绑定事件
        * @access public
        * @param {[  event and field and  function]}  
        * @return null 
        */
        on(eventName,field,callbackFn){
        	if(!field || !eventName || !callbackFn || !$.isFunction(callbackFn)){
        		console.error("参数不全,或参数不正确！")
        		return false;
        	}
        	this.$events[eventName+"."+field] = callbackFn;
        	
        	let that = this;
        	let $el =  this.$el;
        	let $e = this.$el.find(`[form-dataType][name='${field}']`);
        	
        	//搜索类型，值的点击事件
        	if(eventName=="clickSearchValue"){
	        	$e.removeAttr("onValClick").find("u").removeAttr("onclick");
	        	$el.on("click",`[form-dataType][name='${field}'] u`,function(){
	        		var index =$(this).parents(".select-search-input").find("u").index($(this));
	        		var data = $.trim($(this).text());
	        		callbackFn($(this),data,index); 
	        	});
        	}
        	//搜索类型，值的删除事件
        	if(eventName=="removeSearchValue"){
	        	$el.on("click",`[form-dataType][name='${field}'] .span-close`,function(){
	        		var prevNode = $(this).prev();
	        		var index = $(this).parents(".select-search-input").find("u").index(prevNode);
	        		var data = $.trim(prevNode.text());
	        		callbackFn($(this),data,index); 
	        	});
        	}
        }
		
		/**
        * 执行事件
        * @access public
        * @param {[  event and field and  function]}  
        * @return null 
        */
		callEvent( type,name, e, data){
			let event = this.$events[type+"."+name];
			if(event) { event(e, data );}
		}
		
	    /**
        *  获取全局数据
        * @access public
        * @param {[Boolean]}     //是否进行效验，默认为true
        * @return {[Object]}  
        */
        getData(isValid){
        	let that = this;
        	let data =  this.$el.serializeJson();
        	let isValidformIn =true;
            if (isValid === false ){  return data; }
            if(that.$el.find('.layui-tab-item').length>0){
            	$.each(that.$el.find('.layui-tab-item'), function(index,o) {
	        		if(!$(o).validformIn()){
	        			that.$el.find('.layui-tab-item').removeClass("layui-show");
	        			that.$el.find('.layui-tab-title li').removeClass("layui-this");
	        			$(this).addClass("layui-show");
	        			that.$el.find('.layui-tab-title li').eq($(this).index()).addClass("layui-this");
	        			isValidformIn=false;
	        			return true;
	        		}
	        	});
            }else{
            	if(!this.$el.validformIn()){
            		isValidformIn=false;
            	}
            }
        	return  isValidformIn ? data : false;
        }
        
        /**
        * 获取数据
        * @access public
        * @return {[string]}  
        */
        getValue(field){
            return (this.getData(false)[field] || "");
        }
        
        /**
        * 获取富文本的实列对象
        * @access public
        * @param {[string]}  type   // richtext , file
        * @param {[string]}  field   // 字段名称
        * @return {[object]}  
        */
        getRealColumnObj(type,field){
            return this.$el.find(`[form-datatype="${type}"][name="${field}"]`).data("object");
        }
        
        /**
        *  设置FormValue
        * @param {[Object]}     {id:12,gg:"fff" } 
        * @access public
        */
        setFormValue(obj){
        	for (let i in obj) {
        		this.setValue(i,obj[i]);
        	}
        }
        
	    /**
        * 设置数据
        * @access public
        * @return {[Object]}  
        */
        setValue(field,value,name){
        	let that=this;
        	let  formConfig = (window.__webConfig__ && __webConfig__.xw_form) || {};
            let  defaultAcc = formConfig.numberAcc  || 2;
        	let fields= String(field || "").split(',');
        	fields.forEach(function(e){
        		let  $o = that.$el.find(`[name='${e}']`);
        		if(!name && that.$el.find(`[_name='${e}']`).length > 0){
					that.setValue(e,value,true)
				}
        		if(name){ $o = that.$el.find(`[_name='${e}']`); }
        		
        		//地区类型
        		if( that.$el.find(`[region-name='${e}']`).length ){ 
        			$o = that.$el.find(`[region-name='${e}']`);   
        		}
        
        		var $type= $o.attr("data-value",value).attr("form-datatype");
				switch($type){
				    case "text":  
				    case "datetime":
				        $o.val(value);
				        break;
				    case "number": 
				    case "percent":
				    case "money":
				        $o.val( $.commafy( Number(value).toFixed($o.attr("acc") || defaultAcc)));
				        break;
				    case "radio":  case "checkbox":
				    	$o.prop("checked", false);
				    	String(value || "").split(',').forEach(function(val){
				    		that.$el.find(`input[name='${e}'][value='${val}']`)
				    		.attr("checked","true").prop("checked", true);
				    	});
				        break;
				    case "select":
				    	$o.find('option').removeAttr("selected").prop("selected", false);
				    	$o.find(`option[value='${value}']`).attr("selected","true").prop("selected", true);
				        break;
				    case "region":
				    	$o.find(".collect").val( value || '');
				    	that._initEvent("region");
				        break;    
				   	case "multiSelect":
			    		$o.find('option').removeAttr("selected").prop("selected", false);
				    	String(value || "").split(',').forEach(function(val){
				    		$o.find(`option[value='${val}']`).attr("selected","true").prop("selected", true);
				    	});
			    		var datatype=that.$el.find("[fs_id='"+$o.attr("xm-select") +"']").attr("datatype");
			    		layui.formSelects.render();
			    		var  ofsId = that.$el.find("[fs_id='"+$o.attr("xm-select") +"']");
			    		if(datatype){ ofsId.attr("datatype",datatype); }
			    		ofsId.attr("data-value",value);
				        break;
				    case "linkage":    
				        layui.formSelects.value($o.attr("xm-select"),value);
				        that.$el.find("[fs_id='"+$o.attr("xm-select") +"']").attr("data-value",value.join(',') );
				        break;
				    case "search":
					    let html= value == "" ?  "" : String(value).split(',').map(h=>{
					    	let onValClick = $o.attr("onValClick") || "";
					    	let showCloseBtn = $o.attr("showCloseBtn") || "";
					    	let str= `<span><u onclick="${onValClick || $o.attr('onClick') || ''}">${h}</u></span>`;
	                    	if(String(showCloseBtn)!="false"  && $o.attr("edit") !="false" && h){
	                    		str =  `
		                        	<span>
			                        	<u onclick="${onValClick || $o.attr('onClick') || ''}" >${h}</u>
			                        	<sup class="span-close">x</sup>
		                        	</span>	
		                        `;
	                    	}
							return str;
	                    }).join('');
				    	$o.html(html);
				        break;
				    case "img":
                        var newVal =  $o.find('input.collect').val().split(','); 
                        var newVal = $.map(newVal,function(h){ if(h) return h });
                        newVal.push(value);
                        $o.find('input.collect').val( newVal.join(',') );
                        let r =`${__root__}/public/images/loading-1.gif`;
                        let imgVal  = `
                            <div class="layui-form-item-body" style="background: url(${r}) no-repeat center;">
                                <div  class="layui-form-item-img">
                                    <div class="layui-form-item-img-mask">
                                        <i class="iconfont yan">&#xe663;</i>
                                        <i class="iconfont del">&#xe628;</i>
                                        <i class="iconfont edit">&#xe621;</i>
                                    </div> 
                                    <img src='${value}'/>
                                </div>
                            </div>
                        `;
                        $o.find('.layui-form-item-img-upload').before(imgVal);
                        if($o.find(".layui-form-item-body").length >= $o.attr("max") && $o.attr("max") > 0){
                            $o.find('.layui-form-item-img-upload').addClass("hide");
                        }
                        break;      
				    default:
				    	$o.val(value);
				}
        	});
        	
        	clearInterval(this.setValueTimoutide || null);
        	this.setValueTimoutide = setTimeout(  function(){
        		form.render(null,null,'.xw-form');
        	},1);
        }
        
        /**
        * 设置禁用
        * @access public
        */
        setReadonly(field,isReadonly,isReq){
        	let that=this;
        	let fields= String(field || "").split(',');
        	fields.forEach(function(e){
        		let  $o = e == "*" ? that.$el.find(`[form-datatype]`) : 
        		that.$el.find(`[form-datatype][name='${e}']`);
        		if($o.length < 1){ $o = that.$el.find(`[form-datatype][_name='${e}']`); }
        		if($o.length < 1){ $o = that.$el.find(`[form-datatype][region-name='${e}']`); }
        		$.each($o,function(index,h){
        			if(isReadonly){
	        			$(h).removeAttr("disabled").removeAttr("readonly").attr("edit","true");
	        			let vtype =$(h).attr("datatype")  || $(h).data("datatype");
	        			if(isReq || vtype ){
	        				$(h).attr("datatype",vtype || (isReq == true ?  "*" : (isReq || "*")) )
	        				.parents('.table-input').prev().addClass("f-orage");
	        			}
	        		}else{
	        			$(h).data("datatype",$(h).attr("datatype"))
		        		.attr("disabled","disabled").attr("readonly","readonly").attr("edit","false")
		        		.removeAttr("datatype").parents('.table-input').prev().removeClass("f-orage");
	        		}
	        		that.setValue($(h).attr("name"),that.getValue($(h).attr("name")));
        		});
        	});
    		clearInterval( that._setReadonlyTimoutide || null );
    		that._setReadonlyTimoutide = setTimeout(function (){ that._initEvent();},1);
        }
        
        /**
        * 设置必填
        * @access public
        */
        setReq(field,isReq,vType){
        	let that=this;
        	let fields= String(field || "").split(',');
        	fields.forEach(function(e){
        		let  $o = e =="*" ? that.$el.find(`[form-dataType]`) : 
        		that.$el.find(`[form-dataType][name='${e}']`);
        		if($o.length < 1){ $o = that.$el.find(`[form-dataType][_name='${e}']`); }
    			if(isReq){
    				$o.attr("datatype",vType || "*").parents('.table-input').prev().addClass("f-orage");
    				if(e =="*" ){
    					that.$el.find(`[form-dataType='search']`).attr("datatype","chooseBox");
    				}else{
    					that.$el.find(`[form-dataType='search'][name='${e}']`)
    					.attr("datatype","chooseBox");
    				}
        		}else{
        			$o.removeAttr("datatype").parents('.table-input').prev().removeClass("f-orage");
        		}
        	});
        }
        
        /**
        *  设置按钮
        * @access public
        * @param {[id,isDispay]}  
        * @return null 
        */
        setBtn(ids,isDispay){
        	var that=this;
        	if(ids=="*"){
        		if(isDispay==true){
	        		that.$el.find("button").show();
	        	}else if(isDispay==false){
	        		that.$el.find("button").hide();
	        	}
	        	return that.$el.find("button");
        	}else{
        		var ids = String(ids || "").split(',');
	        	ids.forEach(e=>{
	        		if(isDispay==true){
		        		that.$el.find(`#${e}`).show();
		        	}else if(isDispay==false){
		        		that.$el.find(`#${e}`).hide();
		        	}
	        	});
	        	return this.$el.find( ids.map(e=>{  return "#"+e;  }).join(',')  );
        	}
        }
        
        /**
        *  清空数据
        * @access public
        */
        clearData(){
        	for (let i in this.getData(false)) {
        		this.setValue(i,"");
        	}
        }
        
        /**
        *  添加选项数据
        * @access public
        */
        addOption(field,data){
        	let $e = this.$el.find(`[form-dataType][name='${field}']`);
        	$e = $e.length > 0 ? $e : this.$el.find(`[form-dataType][_name='${field}']`);
        	switch ($e.attr("form-dataType")){
        		case 'select':
	                $e.html("").html( data.map(function(h){
	                   return `<option value="${h.value}" >${(h.text || h.label)}</option>`;
	                }));
	                form.render(null,null,'.xw-form');
        			break;
        		case 'multiSelect':
        			let id = $e.attr("xm-select");
	                layui.formSelects.data( id, 'local', {
			            arr: data.map(function(h){
	                  	 	return {
	                  	 		"name": (h.text || h.label), 
	                  	 		"value":h.value,
	                  	 		"type": h.type,
	                  	 		"selected":h.selected ?'selected' : "",
	                  	 		"disabled":h.disabled ?'disabled' : ""
	                  	 	}
	                	})
		        	});
		        	layui.formSelects.btns(id,['select','remove'],{show: '', space: '10px'});
        			break;
        		case 'linkage':
        			let id2 = $e.attr("xm-select");
	                layui.formSelects.data( id2, 'local', {
			            arr: data,
	                	linkage:true
		        	});
		        	layui.formSelects.btns(id2,['select','remove'],{show: '', space: '10px'});
        			break;	
        	}
        }
        
        /**
        *  保存
        * @access public
        * @param {[function or  Number]}  
        * @param {[object]}     //等于2的时候，更新为该对象参数
        * @return null 
        */
        save(callbackFn,obj){
        	var that=this;
            let data=this.getData();
            if(data){
                let p = new Promise(function (resolve, reject) {
                    if(callbackFn && $.isFunction(callbackFn)){
                        callbackFn(resolve, reject,data);
                    }else if($.isNumeric(callbackFn)){
                        resolve(callbackFn);
                    }else{
                        resolve(0);
                    }
                }).then(function (resolve) {
                    let param = {
					 	data: JSON.stringify({ data:data,id: that.$id}),
					}
                    param = $.extend(true,{},that.$request,param);
                    let  formConfig = (window.__webConfig__ && __webConfig__.xw_form) || {};
				    let rep = $.ajaxs(formConfig.save_url,param);
				    rep.then(function (res) {
				    	let hintTrim = 600;
				    	if(resolve === 1 ){
				    		$.toast(1,res.msg,1000);
				    		if(that.opener){
				    			that.opener.$.toast(1,res.msg,hintTrim);
				    		}
				    		setTimeout(function(){  that.close(); },10);
	                    }else if(resolve === 2 && that.$mode !=2 ){ 
	                    	$.toast(1,res.msg,1000);
	                        if(that.opener){
				    			that.opener.$.toast(1,res.msg,hintTrim);
				    		}
	                    	$.setRequest( $.extend( true, {oid:res.data,mode:2} , obj || {} ) );
	                    }else if(resolve === 3 ){
	                    	$.toast(1,res.msg,1000);
	                    	if(that.opener){
				    			that.opener.$.toast(1,res.msg,hintTrim);
				    		}
	                    	$.setRequest( $.extend( true, {oid:res.data,mode:3} , obj || {} ) );
	                    }else if(resolve > 3 ){
	                    	//大于3不做任何动作
	                    }else{
	                    	$.toast(1,res.msg,hintTrim);
	                    }
                		return res;
                	}).catch(function(e){ 
                		
                	});
		            return rep;
				});
				p.catch(function (reason) {
				    return reason;
				});
				return p;
            }else{
                return new Promise(function (resolve, reject) { });
            }
        }
        
        /**
        *  返回父级
        */
        get opener(){
        	return window.opener  || window.parent || {};
        }
        
        /**
        *  关闭窗口
        */
        close(){
        	window.close();
    		parent.layer.close(parent.layer.getFrameIndex(window.name));
        }
    }

    exports('forms',{ render:function(id,opt,xml){ return  new Form(id,opt,xml); } });
});